package gw.com.android.presenter.http;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.interfaces.ReqCallBack;

/**
 * @author jett
 * @since 2017-11-15.
 */
public class HomeTradeRequest {

    private String cacheFileName = "_last_news2.dat";

    public HomeTradeData fetchLocal() {
        String str = CacheUtils.readFile(cacheFileName);
        return parse(str, false);
    }

    public void call(final ReqCallBack<HomeTradeData> callBack) {
        String mUrl = ConfigUtil.instance().getUrlPath("lastTradeNews");
        new Https(mUrl).responseOnUiThread(false).get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                HomeTradeData data = parse(result, true);
                postSuccess(data, callBack);
            }

            @Override
            public void onFailure(Request request, IOException e) {
                postFailure(e, callBack);
            }
        });
    }

    private void postSuccess(final HomeTradeData data, final ReqCallBack<HomeTradeData> callBack) {
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                callBack.onReqSuccess(data);
            }
        });
    }

    private void postFailure(Exception e, final ReqCallBack<HomeTradeData> callBack) {
        final String msg = e == null ? "" : e.getMessage();
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                callBack.onReqFailed(msg);
            }
        });
    }

    private void storeLocal(String str) {
        CacheUtils.writeFile(cacheFileName, str);
    }

    private HomeTradeData parse(String str, boolean cache) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                HomeTradeData data = new HomeTradeData();
                // 日历
                JSONObject calendarJson = dataJson.optJSONObject("calendar");
                if (calendarJson != null) {
                    data.calendarTitle = calendarJson.optString("name");
                    data.hasCalendar = !TextUtils.isEmpty(data.calendarTitle);
                    data.calendarPreview = calendarJson.optString("predictValue");
                    data.calendarForecast = calendarJson.optString("lastValue");
                    data.calendarRating = calendarJson.optInt("importanceLevel");
                }
                // 要闻
                JSONObject newsJson = dataJson.optJSONObject("news");
                if (newsJson != null) {
                    data.mainTitle = newsJson.optString("title");
                    data.hasMain = !TextUtils.isEmpty(data.mainTitle);
                    String content = newsJson.optString("content");
                    data.mainContent = htmlFormat(content);
                }
                // 快讯
                JSONObject kxJson = dataJson.optJSONObject("kx");
                if (kxJson != null) {
                    data.flashContent = htmlFormat(kxJson.optString("title"));
                    data.hasFlash = !TextUtils.isEmpty(data.flashContent);
                }
                // FM
                data.fmArticleId = dataJson.optInt("news_id", -1);
                if (cache) {
                    storeLocal(str);
                }
                return data;
            }
        } catch (JSONException e) {
            Logger.e(e);
        }
        return null;
    }

    private String htmlFormat(String text) {
        if (TextUtils.isEmpty(text)) {
            return text;
        }
        Spanned spanned = Html.fromHtml(text);
        if (spanned != null) {
            text = spanned.toString();
            return text.replaceAll("￼", "");
        }
        return null;
    }

    public class HomeTradeData {

        public boolean hasFlash;
        public String flashContent;

        public boolean hasMain;
        public String mainTitle;
        public String mainContent;

        public boolean hasCalendar;
        public String calendarTitle;
        public int calendarRating;
        public String calendarPreview;
        public String calendarForecast;

        public int fmArticleId;
    }

}
